//
//  CardView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/16.
//

import AlertToast
import Combine
import SwiftUI
import TLCLock

class CardModel: SheetModel {
    var cancellable: AnyCancellable?
    let device: LockDevice

    init(device: LockDevice) {
        self.device = device
    }

    deinit {
        cancellable?.cancel()
        debugPrint("card model deinit")
    }
}

struct CardView: View {
    let model: CardModel
    

    @State var id: String = ""
    @State var forver: Bool = true
    @State var begin: Date = .init()
    @State var end: Date = Date().nextYear
    @State var cardNo: String = ""

    var body: some View {
        VStack {
            Text(model.device.macAddress)
                .bold()
                .foregroundColor(.orange)
                .font(.headline)
                .padding(.horizontal, 20)
                .frame(maxWidth: .infinity, alignment: .center)
            
            YxrInputView("卡索引", text: $id)
            YxrToggleView(title: "永久", isOn: $forver)
            if !forver {
                YxrDatePicker(title: "开始时间", date: $begin)
                YxrDatePicker(title: "结束时间", date: $end)
            }
            YxrInputView("卡号", placeholderText: "仅直接添加卡时生效", text: $cardNo)
            
            YxrActionView(
                data: [
                    (0, "添加卡(刷卡)"),
                    (5, "添加卡(卡号)"),
                    (1, "删除卡"),
                    (2, "更新卡时间"),
                    (3, "冻结卡"),
                    (4, "解冻"),
                    (6, "清空"),
                ],
                itemBuilder: { value in
                    YXRActionItem(text: value.1) {
                        switch value.0 {
                        case 0: startAddCard()
                        case 5: addCardNumber()
                        case 1: deleteCard()
                        case 2: modifyCard()
                        case 3: updateCard(status: .frozen)
                        case 4: updateCard(status: .effective)
                        case 6: clearCard()
                        default:
                            showToast("未实现的方法")
                        }
                    }
                }
            ).padding(.all, 10)
            
            LogView()
        }
        .yxrNavigationTitle("card").onDisappear {
            model.cancellable?.cancel()
            model.cancellable = nil
        }
    }

    func startAddCard() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        Task {
            showLoading()
            let result = await model.device.addCard(begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId) {
                offset, _, cardNo in
                if offset == 0 {
                    showLoading("请刷卡")
                } else {
                    Log.info("已刷卡：cardNo: \(cardNo ?? "null")")
                    if let cardNumber = cardNo {
                        self.cardNo = cardNumber
                    }
                }
            }
            hideLoading()
            if result.isFailure {
                showToast(result.errorMessage)
                return
            }
            showToast("添加门卡成功")
            self.id = "\(result.value!)"
            Log.info("当前卡ID：\(result.value!)")
        }
    }

    func addCardNumber() {
        if cardNo.isEmpty {
            showToast("请输入卡号")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        lockTask(desc: "effective Card") {
            let result = await model.device.addCard(cardNumber: cardNo, begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId)
            if result.isSuccess {
                if let idx = result.value {
                    self.id = "\(idx)"
                }
            }
            return result
        }
    }

    func deleteCard() {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "delete card") {
            let result = await model.device.deleteCard(cardId: idx, lockKey: lockKey, trackId: Server.testTrackId)
            if result.isSuccess {
                self.id = ""
            }
            return result
        }
    }

    func updateCard(status: CardState) {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "update card \(status)") {
            await model.device.changeCardState(cardId: idx, state: status, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func modifyCard() {
        guard let idx = UInt32(id) else {
            showToast("id 错误")
            return
        }

        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }
        
        let from: Date? = forver ? nil : begin
        let to: Date? = forver ? nil : end

        lockTask(desc: "modify") {
            await model.device.modifyCard(cardId: idx, begin: from, end: to, lockKey: lockKey, trackId: Server.testTrackId)
        }
    }

    func clearCard() {
        guard let lockKey = Server.getSecret(model.device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        lockTask(desc: "clear") {
            await model.device.clearAllCard(lockKey: lockKey, trackId: Server.testTrackId)
        }
    }
}
